package com.example.yiparkapplication.activity.index.activity.myCar;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.codingending.popuplayout.PopupLayout;
import com.example.yiparkapplication.R;
import com.example.yiparkapplication.constant.API;
import com.example.yiparkapplication.constant.Constant;
import com.example.yiparkapplication.entity.UserCarVerify;
import com.example.yiparkapplication.util.BaseActivity;
import com.example.yiparkapplication.util.Common;
import com.example.yiparkapplication.util.CompressImage;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddCarDetailsActivity extends BaseActivity implements View.OnClickListener {
    private Handler handler;
    private EditText editText;
    private int imgFlag;
    private String licensePlateImg;
    private String drivingLicenseImg;
    private static String mUserId;

    public static void getUserId(String userId){
        mUserId = userId;
    }

    @SuppressLint("clickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_car_details_layout);
        handler = new Handler();

        editText = findViewById(R.id.id_license_plate);
        //这个原来是点击车牌输入框然后显示自定义的键盘来的
//        editText.setOnTouchListener();

        ImageView licensePlateImg = findViewById(R.id.id_license_plate_img);
        licensePlateImg.setOnClickListener(this);
        LinearLayout whyAddLicensePlate = findViewById(R.id.id_why_add_license_plate);
        whyAddLicensePlate.setOnClickListener(this);
        ImageView addDrivingLicenseImg = findViewById(R.id.id_driving_license_img);
        addDrivingLicenseImg.setOnClickListener(this);

        Button submitAuditButton = findViewById(R.id.id_submit_audit);
        submitAuditButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v){
        switch(v.getId()){
            case R.id.id_license_plate_img:
                imgFlag = 1;
                getImg();
                break;
            case R.id.id_driving_license_img:
                imgFlag = 2;
                getImg();
                break;
            case R.id.id_submit_audit:
                String licensePlate = editText.getText().toString().trim();
                uploadFiles(licensePlate, licensePlateImg, drivingLicenseImg);
                break;
            case R.id.id_why_add_driving_license:
                submitPicture("为什么需要车头车牌照片？", "为防止他人通过网络等非正常途径，获取到您的行驶证照片用于车辆绑定。");
                break;
            case R.id.id_why_add_license_plate:
                submitPicture("为什么需要车头车牌照片？", "为防止他人恶意绑定您的车辆，获取到您的行驶证照片用于车辆绑定。");
                break;

        }
    }

    private void submitPicture(String why, String reason){
        AlertDialog.Builder dialog = new AlertDialog.Builder(AddCarDetailsActivity.this);
        dialog.setTitle(why);
        dialog.setMessage(reason);
        dialog.show();
    }

    private void getImg(){
        View view = View.inflate(AddCarDetailsActivity.this, R.layout.fragment_get_img_button_layout, null);
        final PopupLayout popupLayout = PopupLayout.init(AddCarDetailsActivity.this, view);
        popupLayout.show();

        Button albumButton = view.findViewById(R.id.id_get_img_album);
        albumButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                if (ContextCompat.checkSelfPermission(AddCarDetailsActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(AddCarDetailsActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                }else{
                    openAlbum();
                    popupLayout.dismiss();
                }
            }
        });
        Button cancelButton = view.findViewById(R.id.id_get_img_cancel);
        cancelButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                popupLayout.dismiss();
            }
        });
    }

    private void openAlbum(){
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, Constant.CHOOSE_PHOTO);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResult){
        switch(requestCode){
            case 1:
                if (grantResult.length > 0 && grantResult[0] == PackageManager.PERMISSION_GRANTED){
                    openAlbum();
                }else{
                    Toast.makeText(AddCarDetailsActivity.this, Constant.REFUSED_PERMISSION, Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode){
            case Constant.CHOOSE_PHOTO:
                if (resultCode == RESULT_OK){
                    if (Build.VERSION.SDK_INT >= 19){
                        handleImageOnKitKat(data);
                    }else{
                        handleImageBeforeKtiKat(data);
                    }
                }
        }
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data){
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(AddCarDetailsActivity.this, uri)){
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            }else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        }else if("content".equalsIgnoreCase(uri.getScheme())){
            imagePath = getImagePath(uri, null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            imagePath = uri.getPath();
        }
        displayImage(imagePath);
    }

    private void handleImageBeforeKtiKat(Intent data){
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection){
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null){
            if (cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath){
        ImageView picture;
        if (imagePath != null){
            if (imgFlag == 1){
                picture = findViewById(R.id.id_license_plate_img);
                licensePlateImg = imagePath;
                TextView licensePlateTextView = findViewById(R.id.id_add_license_plate_img_tip);
                licensePlateTextView.setVisibility(View.GONE);
            }else{
                picture = findViewById(R.id.id_driving_license_img);
                drivingLicenseImg = imagePath;
                TextView drivingLicenseTipTextView = findViewById(R.id.id_driving_licenses_img_tip);
                drivingLicenseTipTextView.setVisibility(View.GONE);
            }
            picture.setImageURI(Uri.parse(imagePath));
        }else{
            Toast.makeText(AddCarDetailsActivity.this, Constant.FAILED_TO_GET_IMAGE, Toast.LENGTH_LONG).show();
        }
    }

    private void uploadFiles(final String licenseplate, final String licensePlateImg, final String drivingLicenseImg){
        //先应该对三个参数进行判空处理
        MediaType mediaType = MediaType.parse("multipart/form-data; charset=utf-8");
        List<String> files = new ArrayList<String>();
        files.add(licenseplate);
        files.add(drivingLicenseImg);
        MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("type", "3");
        for (int i=0;i<files.size();i++){
            Bitmap bitmap = CompressImage.getImage(files.get(i));
            File file = CompressImage.getFile(bitmap, i);
            requestBodyBuilder.addFormDataPart("files", file.getName(), RequestBody.create(mediaType, new File(files.get(i))));
        }
        RequestBody requestBody = requestBodyBuilder.build();
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_POST_UPLOAD_FILES)
                .post(requestBody)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)throws IOException{
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    JSONArray ja = joOut.getJSONArray("object");
                    String licensePlateImg = ja.get(0).toString();
                    String drivingLicenseImg = ja.get(1).toString();
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), "图片上传成功", Toast.LENGTH_LONG).show();
                    submitAudit(licenseplate, licensePlateImg, drivingLicenseImg);
                    Looper.loop();
                }else{
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
            }
        });
    }

    private void submitAudit(String licensePlate, String licensePlateImg, String drivingLicenseImg){
        licensePlate = licensePlate.toUpperCase();
        UserCarVerify userCarVerify = new UserCarVerify();
        userCarVerify.setPlate(licensePlate);
        userCarVerify.setUserId(mUserId);
        userCarVerify.setDriverLicensePhoto(drivingLicenseImg);
        userCarVerify.setPlatePhoto(licensePlateImg);

        String json = JSONObject.toJSONString(userCarVerify);
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_USER_CAR_VERIFY)
                .post(requestBody)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)throws IOException{
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    Looper.prepare();
                    //Toast.makeText(getApplicationContext(),"提交成功", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }else{
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }
        });
    }

}
